﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OneDollarStore.Models;

namespace OneDollarStore.Controllers
{
    public class CheckoutController : Controller
    {
        StoreModelEntities storeDB = new StoreModelEntities();
        
        // URL: /Admin/Checkout/
        public RedirectToRouteResult Index()
        {
            return RedirectToAction("AddressAndPayment");
        }

        [Authorize]
        public ActionResult AddressAndPayment()
        {
            var cart = ShoppingCartModel.GetCart(this.HttpContext);
            if (cart.GetCount() == 0)
            {
                return RedirectToAction("Index", "ShoppingCart");
            }
            Order order = new Order
            {
                OrderDate = DateTime.Now,
                Username = User.Identity.Name
            };
            return View(order);
        }

        [HttpPost]
        public ActionResult AddressAndPayment(Order order)
        {
            TryUpdateModel(order);
            try
            {
                order.Username = User.Identity.Name;
                order.OrderDate = DateTime.Now;
                storeDB.AddToOrders(order);
                storeDB.SaveChanges();
                // Save order
                var cart = ShoppingCartModel.GetCart(this.HttpContext);
                cart.CreateOrderDetails(order);
                return RedirectToAction("CheckoutComplete", new { id = order.OrderID });
            }
            catch
            {
                return View(order);
            }
        }

        public ActionResult CheckoutComplete(int id)
        {
            var order = storeDB.Orders.FirstOrDefault(o => o.OrderID == id);
            if (order == null)
            {
                return RedirectToAction("AddressAndPayment");
            }
            var orderDetails = from orderDetail in storeDB.OrderDetails
                               .Include("SerialProduct")
                               where orderDetail.Order.OrderID == id
                               select orderDetail;
            var viewModel = new CheckoutViewModel
            {
                Order = order,
                Details = orderDetails.ToList()
            };
            return View(viewModel);
        }
    }
}